package cn.lyjuan.archetypes.bms.web.controller;


import cn.lyjuan.archetypes.bms.web.cst.SessionConst;
import cn.lyjuan.archetypes.bms.web.property.SysProperties;
import cn.lyjuan.base.util.StringUtils;
import cn.lyjuan.archetypes.bms.web.bean.dto.GroupActionBean;
import cn.lyjuan.archetypes.bms.common.entity.MgManage;
import cn.lyjuan.archetypes.bms.web.service.ActionService;
import cn.lyjuan.archetypes.bms.web.controller.base.SecurityController;
import cn.lyjuan.archetypes.bms.web.service.ManageService;
import cn.lyjuan.archetypes.bms.web.util.SessionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by chad on 2016/3/9.
 */
@Controller
public class IndexController extends SecurityController
{
    private static Logger log = LogManager.getLogger(IndexController.class.getName());

    @Autowired
    private SysProperties sysProperties;

    @Autowired
    @Qualifier("mgActionService")
    private ActionService actionSer;

    @Autowired
    @Qualifier("mgManageService")
    private ManageService manageSer;

    @RequestMapping("/")
    public ModelAndView index(Model model)
    {
        MgManage manage = manageSer.queryManageByName(this.getUserName());

        // 获取权限信息
        List<GroupActionBean> actions = actionSer.queryActionsForManage(manage, true);

        // 放入 session
        SessionUtils.set(SessionConst.USER_MENU, actions);

        if (log.isDebugEnabled())
            log.debug("index groups >> " + cn.lyjuan.base.util.StringUtils.toStr(actions));

        return new ModelAndView("/index");
    }

    /**
     * 跳转JSP
     *
     * @param path
     * @param viewName
     * @return
     */
    @RequestMapping("to/{path}/{viewName}")
    public String toJsp(@PathVariable String path, @PathVariable String viewName,
                        HttpServletResponse resp)
    {
        if (StringUtils.isNull(path)
                || StringUtils.isNull(viewName))
        {
            resp.setStatus(HttpStatus.NOT_FOUND.value());
            return Integer.toString(HttpStatus.NOT_FOUND.value());
        }

        // 参数不合法
        if (!path.matches("^[a-zA-Z0-9_]+$")
                || !viewName.matches("^[a-zA-Z0-9_]+$"))
        {
            resp.setStatus(HttpStatus.NOT_FOUND.value());
            return Integer.toString(HttpStatus.NOT_FOUND.value());
        }

        return path + "/" + viewName;
    }
}
